const Users = require('../db/index').Users

const createToken = require('../utils/createToken.js') // 创建token
const checkToken = require('../utils/checkToken.js') // 验证token

let loginIn = async (ctx) => {
    const { username, password } = ctx.request.body
    console.log(1);
    let doc = await Users.findOne({username:username})
    // let doc = await Users.find()
    console.log(username,doc)
    if (!doc) {
        ctx.body = {
            code: -1,
            msg: '用户名不存在'
        }
    } else if (doc.password !== password) {
        ctx.body = {
            code: -1,
            msg: '密码错误'
        }
    } else if (doc.password === password) {
        console.log('密码正确')
        let token = createToken(username) // 生成token 
        doc.token = token // 更新mongo中对应用户名的token
        try {
            await doc.save() // 更新mongo中对应用户名的token
            ctx.body = {
                code: 0,
                msg: '登录成功',
                userinfo:{
                    id:doc._id,
                    username,
                    token
                }
            }
        } catch (err) {
            ctx.body = {
                code: -1,
                msg: '登录失败，请重新登录'
            }
        }
    }
}

const authFunc = {
    loginIn
};
module.exports = authFunc